﻿using System;
using System.Windows;
using Phoenix.Frames.Transitions;
using Transitionals.Controls;

namespace Phoenix.Frames
{
    [TemplatePart(Name = "TransitionElement", Type = typeof(TransitionNavigationFrame))]
    public class TransitionNavigationFrame : NavigationFrame
    {
        const string TransitionElementPartName = "TransitionElement";
        TransitionElement transitionElement;
        bool navigatingForward;

        static TransitionNavigationFrame()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(TransitionNavigationFrame), new FrameworkPropertyMetadata(typeof(TransitionNavigationFrame)));
        }

        public override void NavigateTo(NavigationRequest navigationRequest)
        {
            navigatingForward = true;
            base.NavigateTo(navigationRequest);
        }

        public override void NavigateBack()
        {
            navigatingForward = false;
            base.NavigateBack();
        }

        public override void NavigateBackTo(string controller, string action)
        {
            navigatingForward = false;
            base.NavigateBackTo(controller, action);
        }

        public override void NavigateBackTo(string assembly, string controller, string action)
        {
            navigatingForward = false;
            base.NavigateBackTo(assembly, controller, action);
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            transitionElement =
                GetTemplateChild(TransitionElementPartName) as TransitionElement ??
                Template.FindName(TransitionElementPartName, this) as TransitionElement;
            if (Content != null)
            {
                OnContentChanged(null, Content);
            }
        }

        protected override void OnContentChanged(object oldContent, object newContent)
        {
            base.OnContentChanged(oldContent, newContent);
            TransitionService.TransitionContent(oldContent, newContent, transitionElement, navigatingForward);
        }
    }
}